var json = {
				"keywords":"",
				"fields":"",
				"filters":[]
				};
var searchForm;
var subTypeCombo,vTypeCombo,searchFieldCombo,searchTypeCombo;
var timeFrom,timeTo;
var sortType;
var searchDs;
function displaySearchPreview(){
	Ext.form.Field.prototype.msgTarget = 'side';
	Ext.QuickTips.init();
	var searchFieldDs = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url: DISPATCH_URL}),
		reader: new Ext.data.JsonReader({
			root: 'searchFields',
			id:   'id',
			fields:[
				{name: 'name'},
				{name: 'description'}
			]
		})
	});
	searchFieldDs.baseParams={cmd:'searchConfig','action':'findForCombo'};
	searchFieldCombo = new Ext.form.MultiComboBox({
		id: 'searchFieldCombo',
		name: 'searchFieldCombo',
		editable:false,
        displayField: 'description',  
        valueField: 'name',
        labelSeparator:':',  
        displaySeparator:' ',  
        valueSeparator:' ',  
        mode: 'local', 
        loadingText:'loading...', 
        store: searchFieldDs,
        hiddenName:'test',
        triggerAction: 'all',  
        emptyText:'可选多个...',  
        fieldLabel: '搜索域',
        allowBlank:true,
		listeners:{'change':comboBoxCommonListener}
	});
	var searchTypeDs = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url: DISPATCH_URL}),
		reader: new Ext.data.JsonReader({
			root: 'types',
			id: 'id',
			fields:[
			{name:'id'},
			{name:'name'},
			{name:'description'}
			]
		})
	});
	searchTypeDs.baseParams = {cmd:'type',action:'find'};
	searchTypeCombo = new Ext.form.MultiComboBox({
		id:'searchTypeCombo',
		name:'searchTypeCombo',
		editable:false,
		displayField:'description',
		valueField:'name',
		labelSeparator:':',
		displaySeparator:' ',
		valueSeparator: ' ',
		hiddenName:'test',
		mode:'local',
		store:searchTypeDs,
		triggerAction: 'all',
		emptyText:'可选多个',
		fieldLabel: '类型',
		listeners:{'change':comboBoxCommonListener}
	});
	var subTypeDs =  new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url: DISPATCH_URL}),
		reader:new Ext.data.JsonReader({
			root: 'subTypes',
			id:   'id',
			fields: [
				{name: 'id'},
				{name: 'name'}
			]
		})
	});
	subTypeDs.baseParams = {'cmd':'subType','action':'find'};
	subTypeCombo = new Ext.form.MultiComboBox({
		 		id: 'subTypeCombo',
		 		name: 'subTypeCombo',
		 		editable:false,
                displayField: 'name',  
                valueField: 'name',
                labelSeparator:':',  
                displaySeparator:' ',  
                valueSeparator:' ',  
                mode: 'local',  
                hiddenName:'test',  
                store: subTypeDs,
                triggerAction: 'all',  
                emptyText:'可选多个...',  
                fieldLabel: '子类型',
                listeners:{'change':comboBoxCommonListener}
	});
	var vtypeDs = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({url:DISPATCH_URL}),
		reader: new Ext.data.JsonReader({
			root: 'p_types',
			fields: [
				{name: 'name'},
				{name:'code'}
			]
		})
	});
	vtypeDs.baseParams={'cmd':'keysubject','action':'findPType'};
	vTypeCombo = new Ext.form.MultiComboBox({
		 		id: 'vTypeCombo',
		 		editable:false,
		 		name: 'vTypeCombo',
                displayField: "name",  
                valueField: 'code',
                labelSeparator:':',  
                displaySeparator:' ',  
                valueSeparator:' ',  
                mode: 'local',  
                hiddenName:'test',  
                store: vtypeDs,
                triggerAction: 'all',  
                emptyText:'可选多个...',  
                fieldLabel: '垂直分类',
                listeners:{'change':comboBoxCommonListener}
	});
	timeFrom =  new Ext.form.DateField({
                					fieldLabel: '时间范围',//'<b style="color:red;">* </b>时间范围'
					                id: 'fromTime',
					                name: 'fromTime',
					                format:"Y-m-d G:i"
//					                listeners:{'change':comboBoxCommonListener}
                				});
    timeTo =  new Ext.form.DateField({
    								 hideLabel:true,
		 							labelWidth:0,
					                id: 'timeTo',
					                name: 'timeTo',
					                format:"Y-m-d G:i",
					                listeners:{'change':comboBoxCommonListener}
                				});
    sortType = new Ext.form.ComboBox({
    	id:'sortType',
    	name:'sortType',
    	displayField: "value",  
        valueField: 'value',
        mode: 'local',  
    	store: new Ext.data.SimpleStore({
    		fields:['label','value'],
    		data:  [
					  ['0','auto'],
					  ['1','time'],
					  ['1','relative']
				   ]
    	}),
        triggerAction: 'all',  
        fieldLabel: '排序方式',
        listeners:{'change':comboBoxCommonListener}
    });
    var siteDs = new Ext.data.Store({
		proxy:new Ext.data.HttpProxy({url: DISPATCH_URL}),
		reader: new Ext.data.JsonReader({
			root: 'sites',
			id: 'id',
			fields: [
				{name: 'id'},
				{name: 'name'},
				{name: 'code'}
			]
		})
	});
	siteDs.baseParams = {cmd:'site',action:'find'};
	siteDs.on('load',function(store){
		siteCombo.setValue(BestvSearch.sc);
//		if(store.getCount() == 1){
			vtypeDs.load({params:{sc:BestvSearch.sc}});
			searchFieldDs.load({params:{sc:BestvSearch.sc}});
			searchTypeDs.load({params:{sc:BestvSearch.sc}});
//		}
	});
	var siteCombo = new Ext.form.ComboBox({
				id: 'siteCb',
				name: 'siteCb',
				fieldLabel:'切换驻地',
				mode: 'local',
				forceSelection: true, 
				displayField:'name',
				valueField:'code',
				emptyText:'--切换驻地--',
				width:85, 
				triggerAction: 'all', 
				selectOnFocus:true,
				triggerClass: 'x-form-trigger2',
				store: siteDs,
				lazyInit:false,
				editable: false
	});
	
	siteCombo.on('select',function(combo,record){
		if(record.get('code') == BestvSearch.sc) return;
		BestvSearch.sc = record.get('code');
		vtypeDs.load({params:{sc:BestvSearch.sc}});
		searchFieldDs.load({
							params:{sc:BestvSearch.sc},
							callback:function(r,options,success){
								if(searchFieldDs.reader.jsonData == '')
								{
									Ext.MessageBox.alert(TXT_common_hint, TXT_common_relogin,function() {window.location.href = '../eni/common/logout.jsp';});
									return;
								}
							}});
		searchTypeDs.load({params:{sc:BestvSearch.sc}});
		if(!searchForm.getForm().isValid()){return;}
		else if(setJsonValue()==false){return;}
		else search(json);
	});
	siteDs.baseParams = {cmd:'site',action:'find'};
	siteDs.on('load',function(){
		siteCombo.setValue(BestvSearch.sc);
	});
	searchForm = new Ext.FormPanel({
		labelAlign: 'right',
		border:false,
		region: 'north',
		labelWidth:75,
	    height: 95	,
	    margins: '2 0 0 0',
		frame:true,
		items:[	
				{	
					layout:'column',
					items:[
							{
								columnWidth:.5,
								height: 30,
								layout: 'form',
								defaultType: 'textfield',
								defaults:{anchor:'99%'},
								items:[
									    new Ext.form.TextField({
									    	fieldLabel: '<b style="color:red;">* </b> 关键字',
									    	id: 'skey',
									    	name: 'skey',
									    	allowBlank:false,
											listeners: {
					                            specialkey:function(field,e){
					                            	if(e.getKey() == e.ENTER)
					                            	{
					                            		if(!searchForm.getForm().isValid()){
															Ext.MessageBox.alert(TXT_common_hint,'输入有误，请检查！');
					                            			return;
					                            		}
					                            		if(setJsonValue()==false){
															return ;
														}
					                            		search(json);
					                            	}
					                            }
					                        }
									    })
									  ]
							},
							{
								columnWidth:.25,
								height: 30,
								layout:'form',
								html:'<span><font color="blue" >*多个关键字之间用空格隔开</font></span>'
							},
							{
								columnWidth:.25,
								height: 30,
								layout:'form',
								items:[siteCombo]
							}
						  ]
					
				},	
				{
					layout: 'column',
					items:[
							{columnWidth:.4,layout:'form',defaults:{anchor:'99%'},items:[searchFieldCombo]},
							{columnWidth:.4,layout:'form',defaults:{anchor:'98%'},items:[searchTypeCombo]}
						  ]
				},
				{
					layout: 'column',
					items:[
//							{columnWidth:.4,layout:'form',defaults:{anchor:'99%'},items:[subTypeCombo]},
							{columnWidth:.4,layout:'form',defaults:{anchor:'99%'},items:[vTypeCombo]},
							{columnWidth:.236,layout:'form',defaults:{anchor:'96%'},items:[timeFrom]},
							{columnWidth:.01,layout:'form',defaults:{anchor:'96%'},html:'~'},
							{columnWidth:.155,layout:'form',defaults:{anchor:'96%'},items:[timeTo]}
						  ]
				}
//				{
//					layout: 'column',
//					items: [
//							{columnWidth:.236,layout:'form',defaults:{anchor:'98%'},items:[timeFrom]},
//							{columnWidth:.01,layout:'form',defaults:{anchor:'98%'},html:'~'},
//							{columnWidth:.155,layout:'form',defaults:{anchor:'98%'},items:[timeTo]}
//							{columnWidth:.2,layout:'form',defaults:{anchor:'98%'},items:[sortType]}
//						   ]
//				}
			]
	});
	searchDs = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url: DISPATCH_URL
		}),
		reader: new Ext.data.JsonReader({
			root: 'results',
			totalProperty: 'totalCount',
			id:   'id',
			fields:[
						{name: 'id'},
					    {name: 'name'},
					    {name: 'type'},
					    {name: 'p_type'},
					    {name: 'updateTime'},
					    {name: 'keywords'},
					    {name: 'tags'},
					    {name: 'actors'},
					    {name: 'directors'},
					    {name: 'description'}
				   ]
		})
	});
	
	var searchSm =new Ext.grid.RowSelectionModel({singleSelect:true});
	var searchCm = new Ext.grid.ColumnModel([
		new Ext.grid.RowNumberer(),
		{header:TXT_info_name,dataIndex:'name',width:195,renderer:function(v){
			if(v.length > 10)
				return "<div ext:qtip='"+v+"'>" +  v.substring(0,10)+"..</div>";
			return v; 
		}},
		{header:TXT_info_type,dataIndex:'type',width:65,renderer:function(v){
			if(v.length > 3)
				return "<div ext:qtip='"+v+"'>" +  v.substring(0,3)+"..</div>";
			return v; 
		}},
		{header:TXT_info_p_type,dataIndex:'p_type',width:70,renderer:function(v){
			if(v.length > 3)
				return "<div ext:qtip='"+v+"'>" +  v.substring(0,3)+"..</div>";
			return v; }
		},
		{header:'更新时间',dataIndex:'updateTime',width:112,renderer:function(v){return "<div ext:qtip='"+v+"'>" +  v.substring(2,10)+"..</div>";}},
		{header:'关键字',dataIndex:'keywords',width:170,renderer:function(v){
			if(v.length > 7)
				return "<div ext:qtip='"+v+"'>" +  v.substring(0,6)+"..</div>";
			return v; 
		}},
		{header:'标签',dataIndex:'tags',width:70,renderer:function(v){
			if(v.length > 5)
				return "<div ext:qtip='"+v+"'>" +  v.substring(0,4)+"..</div>";
			return v; 
		}},
		{header:'演员',dataIndex:'actors',width:65,renderer:function(v){
			if(v.length > 3)
				 return "<div ext:qtip='"+v+"'>" +  v.substring(0,3)+"..</div>";
			return v;
		}},
		{header:'导演',dataIndex:'directors',width:65,renderer:function(v){
			if(v.length > 3)
				 return "<div ext:qtip='"+v+"'>" +  v.substring(0,3)+"..</div>";
			return v;
		}},
		{header:TXT_info_description,dataIndex:'description',width:10,
			renderer:function(v){  
			if(v == '') return "<div style='background:#00ffff;' ext:qtip='无简介'>.....</div>";
				return "<div style='background:#00ffff;' ext:qtip='"+v+"'>.....</div>";
			
		}}
	]);
		var searchGrid = new Ext.grid.GridPanel(
		{
			border:false,
			region: 'center',
			ds: searchDs,
			cm: searchCm,
			sm: searchSm,
			stripeRows: true,
			loadMask: {msg:'searching...'},
			viewConfig:{forceFit:true},
			bbar: new Ext.PagingToolbar(
				{
					pageSize: 15,
					height:18,
					store: searchDs,
					displayInfo: true,
					displayMsg: TXT_common_paging,
					emptyMsg: TXT_common_no
				})
		}
	);
	var mainPanel1 = new Ext.Panel({
		border: false,
		region: 'center',
		layout:'border',
		margins:'5 5 5 5',
		cmargins:'5 5 5 5',
		items: [searchForm,searchGrid]
	});
	BestvSearch.glb_mainPanel.add(mainPanel1);
	BestvSearch.drawMainFrame(TXT_app_name + ' - ' + TXT_search_title,siteDs);
}

Ext.onReady(displaySearchPreview);
function search(json){
//	var jsonStr = '{"keywords":"' + json.keywords + '","fields":"' + json.fields + '","filters":[';
//	var filtersArray = json.filters;
//	for(i = 0; i < filtersArray.length; ++i){
//		jsonStr += '{"filterField":'+filtersArray[i].filterField + ',"filterType":' + filtersArray[i].filterType + ',"filterValue":'+filtersArray[i].filterValue+'}';
//		if( i != filtersArray.length - 1)
//			jsonStr +=',';
//	}
//	jsonStr += ']}';	
	searchDs.removeAll();
	searchDs.baseParams = {cmd:'search',action:'searchPreview',json:Ext.util.JSON.encode(json),sc:BestvSearch.sc};
	searchDs.load({
					params:{start:0, limit:15,acs_type:'searchPreview'},
					callback:function(r,options,success){
							if(searchDs.reader.jsonData == '')
							{
								Ext.MessageBox.alert(TXT_common_hint, TXT_common_relogin,function() {window.location.href = '../eni/common/logout.jsp';});
								return;
							}
						}	
				});
}
function initJsonValue(){
	json = {
				"keywords":"",
				"fields":"",
				"filters":[]
//				"order":""
				};
}
function setJsonValue(){
	initJsonValue();
	if(searchTypeCombo.hiddenField.value != '')
		json.filters.push( {"filterField":"type","filterValue":searchTypeCombo.hiddenField.value()} );
	if(vTypeCombo.hiddenField.value != '')
		json.filters.push( {"filterField":"p_type","filterValue":vTypeCombo.getValue()} );
	var filterUpdateTime='min TO max';
	var tf = Ext.util.Format.date(timeFrom.getValue(),'Y-m-d G:i');
	var tt = Ext.util.Format.date(timeTo.getValue(),'Y-m-d G:i');
	if(tf != ''){
		var tfs = tf.split(' ');
		if(tfs.length != 2){
			Ext.MessageBox.alert(TXT_common_hint,'时间格式错误，正确格式为：yyyy-MM-dd HH:mm');
			return false;
		}
		tfs[0] = tfs[0].replace(/-/g,'');
		tfs[1] = tfs[1].replace(':','');
		if(tfs[1].length == 3)
		  tfs[1] = '0'+tfs[1];
		tf = tfs[0]+ tfs[1]; 
		filterUpdateTime = filterUpdateTime.replace("min",tf);
	}
	if(tt != '')
	{
		var tts = tt.split(' ');
		if(tts.length != 2){
			Ext.MessageBox.alert(TXT_common_hint,'时间格式错误，正确格式为：yyyy-MM-dd HH:mm');
			return false;
		}
		tts[0] = tts[0].replace(/-/g,'');
		tts[1] = tts[1].replace(':','');
		if(tts[1].length == 3)
		  tts[1] = '0'+tts[1];
		tt = tts[0]+ tts[1]; 
		filterUpdateTime = filterUpdateTime.replace("max",tt);
		if(tt < tf){
			Ext.MessageBox.alert(TXT_common_hint,'时间错误，起始时间应该小于结束时间！');
			return false;
		}
	}
	if(filterUpdateTime !== 'min TO max')
		json.filters.push({"filterField":"updateTime","filterValue":filterUpdateTime});
	if(searchForm.findById('skey').getValue() == ''){
		Ext.MessageBox.alert(TXT_common_hint,'输入有误，搜索关键字不能为空');
		return false;
	}
	json.keywords = searchForm.findById('skey').getValue();
	json.fields = searchFieldCombo.hiddenField.value;
}
function comboBoxCommonListener(){
	if(!searchForm.getForm().isValid())
		return;
	if(setJsonValue()==false)
		return ;
	search(json);
}